package com.ggs.controller;

import com.ggs.DTO.UserDTO;
import com.ggs.pojo.Article;
import com.ggs.service.ArticleService;
import com.ggs.utils.JwtUtils;
import com.ggs.vo.PageVO;
import com.ggs.vo.ResultVO;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    // token的使用
    @GetMapping("/list")
    public ResultVO list(@RequestHeader(name="Authorization") String token,
                         HttpServletResponse response){
        // 验证token
        try {
            Map<String, Object> claims = JwtUtils.parseToken(token);
            return ResultVO.success("获得头条信息");
        } catch (Exception e) {
            // 相应状态401
            response.setStatus(401);
            return ResultVO.error("未登陆");
        }

    }

//    新增文章(发布文章)
    @PostMapping
    public ResultVO add(@RequestBody @Validated(Article.Add.class) Article article){
        articleService.add(article);
        return ResultVO.success();
    }

//    分页查询文章
    @GetMapping
    public ResultVO list(Integer pageNum, Integer pageSize,
                         @RequestParam(required = false) Integer categoryId,
                         @RequestParam(required = false) String state){
        System.out.println("=========!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!========"+pageNum);
        System.out.println("=========!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!========"+pageSize);
        PageVO pageVO = articleService.list(pageNum, pageSize, categoryId, state);
        return ResultVO.success(pageVO);
    }
//    获取文章详情
    @GetMapping("/detail")
    public ResultVO detail(Integer id){
        Article article = articleService.detail(id);
        return ResultVO.success(article);
    }

//    更新文章
    @PutMapping
    public ResultVO updateArticle(@RequestBody @Validated(Article.Update.class)  Article article){
        articleService.update(article);
        return ResultVO.success();
    }

//    删除文章
    @DeleteMapping
    public ResultVO delete(@NotNull Integer id){
        articleService.delete(id);
        return ResultVO.success();
    }
}
